package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.example.bean.crm.cgdd;
import com.example.bean.crm.cgddmx;
import com.example.bean.k3.ssdd;
import com.example.service.crmService.crmService;
import com.example.service.k3Service.k3Service;
import com.example.utils.k3Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Map;

/**
 * 采购订单
 * Created by tony on 2017/12/15.
 */
@Component
@RestController
public class CgddSqlControl {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //定义k3Service
    @Autowired
    private k3Service k3Service;
    //定义mesService
    @Autowired
    private crmService crmService;

    /**
     * 取得中间表采购信息，生成销售订单
     */
    @RequestMapping("/insertSo")
    @Scheduled(cron = "0 0/1 * * * ?") //每5执行一次
    public void insertSoScheduled() {
        logger.info("销售订单更新。开始……");
        //取得要处理的销售订单
        ArrayList<cgdd> cgddList = crmService.selectCgdd();
        //遍历销售订单
        for (cgdd cgdd : cgddList) {
            try {
                //是否已存入erp
                String erpFlg = cgdd.getERPxsddbh();
                //更新
                if (erpFlg == null || erpFlg.isEmpty() || erpFlg.equals("")) {
                    //新增
                    k3Service.insertSo(cgdd);
                    Map<String, Object> seorder = k3Service.selectSoInformation(cgdd.getCgddID());
                    //取得销售订单明细
                    ArrayList<cgddmx> cgddmxList = crmService.selectCgddmx(cgdd.getCgddID());
                    String FBillNo = seorder.get("FBillNo").toString();
                    String FInterID = seorder.get("FInterID").toString();
                    if(cgddmxList.size()==0){
                        //删除销售订单
                        k3Service.deleteSo(cgdd.getCgddID());
                        //异常
                        cgdd.setClyf(3);
                        //返回信息
                        cgdd.setRtnInfo("采购订单没有明细数据！");
                        logger.error(cgdd.getCgddID()+"采购订单没有明细数据！");
                    }else{
                        //生成销售订单
                        for (cgddmx cgddmx : cgddmxList) {
                            cgddmx.setERPxxddmxID(FInterID);
                            k3Service.insertSoEntry(cgddmx);
                        }
                        //已经成功添加
                        cgdd.setClyf(2);
                        //返回erpid
                        cgdd.setERPxsddbh(FBillNo);
                        //返回信息
                        cgdd.setRtnInfo("生成成功");
                        logger.info(cgdd.getCgddID()+"生成销售订单："+FBillNo+"成功！");
                    }

                } else {
                    //CRM订单状态 1正常，2删除
                    int crmddzt = cgdd.getCrmddzt();
                    if (crmddzt == 2) {
                        deleteSo(cgdd);
                    }
                }
            } catch (Exception e) {
                //删除销售订单
                k3Service.deleteSo(cgdd.getCgddID());
                logger.error(cgdd.getCgddID()+e.getMessage());
                //异常
                cgdd.setClyf(3);
                //返回信息
                cgdd.setRtnInfo("异常操作，请联系管理员，查看数据属否正确");
            }
            crmService.cggdFlagRturn(cgdd);
        }

        logger.info("销售订单更新。结束……");
    }

    public String token = "";

    /**
     * 获取Token
     */
    public boolean GetToken() {
        k3Api k3Api = new k3Api();
        String getTokenResult = k3Api.getToken();
        //解析结果
        Map result = (Map) JSON.parse(getTokenResult);
        if (result.get("StatusCode").toString().equals("200")) {
            Map data = (Map) JSON.parse(result.get("Data").toString());
            //设置token值
            token = data.get("Token").toString();
            logger.info("Token取得成功，token值：" + token);
            return true;
        } else {
            logger.info("Token取得失败，请检查网络");
            return false;
        }
    }

    /**
     * 删除erp中销售订单
     */
    @RequestMapping("/deleteSo")
    public void deleteSo(cgdd cgdd) {
        if (GetToken()) {
            //new
            k3Api k3Api = new k3Api();
            //操作url
            String operation = "SO/Delete";
            try {
                //param
                String param = "{" +
                        "  \"Data\": {" +
                        "    \"FBillNo\": \"" + cgdd.getERPxsddbh() + "\"" +
                        "  }" +
                        "}";
                logger.info("删除销售订单："+cgdd.getERPxsddbh());
                //解析结果
                Map result = (Map) JSON.parse(k3Api.callK3Api(operation, token, param));
                logger.info(result.toString());
                if (result.get("StatusCode").toString().equals("200")) {
                    //已经成功添加
                    cgdd.setClyf(2);
                    //返回信息
                    cgdd.setRtnInfo("删除成功！");

                } else {
                    //添加失败
                    cgdd.setClyf(3);
                    //返回信息
                    cgdd.setRtnInfo(result.get("Message").toString());
                }

            } catch (Exception e) {
                logger.error(e.getMessage());
                //异常
                cgdd.setClyf(3);
                //返回信息
                cgdd.setRtnInfo("异常操作，请联系管理员");
            }
            crmService.cggdFlagRturn(cgdd);
        }
    }

    @RequestMapping("/updateCrmSo")
    @Scheduled(cron = "0 0/1 * * * ?") //每1执行一次
    public void updateCrmSo() {

        logger.info("CRM采购订单订单更新。开始……");
        try {
            //取得要处理的销售订单
            ArrayList<cgdd> cgddList = k3Service.selectSo();
            //遍历销售订单
            for (cgdd cgdd : cgddList) {
                crmService.cggdFlagRturn(cgdd);
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        logger.info("CRM采购订单订单更新。结束……");
    }
}
